import collections
from typing import Optional


class LRUCache:
    def get(self, key: int) -> int:
        raise NotImplementedError

    def put(self, key: int, val: int) -> None:
        raise NotImplementedError

class solution1(LRUCache, collections.OrderedDict):
    def __init__(self, capacity: int):
        super().__init__()
        self.capacity = capacity

    def get(self, key: int) -> int:
        if key not in self:
            return -1
        self.move_to_end(key)
        return self[key]

    def put(self, key: int, val: int) -> None:
        if key in self:
            self.move_to_end(key)
        self[key] = val
        if len(self) > self.capacity:
            self.popitem(last=False)


class DLinkedNode:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev: Optional[DLinkedNode] = None
        self.next: Optional[DLinkedNode] = None


class solution2(LRUCache):

    def __init__(self, capacity: int):
        self.cache: dict[int, DLinkedNode] = dict()
        self.head = DLinkedNode()
        self.tail = DLinkedNode()
        self.head.next = self.tail
        self.tail.prev = self.head
        self.capacity = capacity
        self.size = 0

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self.moveToHead(node)
        return node.val

    def put(self, key: int, val: int) -> None:
        if key not in self.cache:
            node = DLinkedNode(key, val)
            self.cache[key] = node
            self.addToHead(node)
            self.size += 1
            if self.size > self.capacity:
                removed = self.removeTail()
                self.cache.pop(removed.key)
                self.size -= 1
        else:
            node = self.cache[key]
            node.val = val
            self.moveToHead(node)

    def addToHead(self, node: DLinkedNode):
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def moveToHead(self, node: DLinkedNode):
        self.removeNode(node)
        self.addToHead(node)

    def removeNode(self, node: DLinkedNode):
        node.prev.next = node.next
        node.next.prev = node.prev

    def removeTail(self) -> DLinkedNode:
        node = self.tail.prev
        self.removeNode(node)
        return node
